package dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import entity.Goods;
import entity.Order;
import entity.OrderItem;
import tools.DBTools;


public class OrderItemDao {
	//根据订单号返回订单下的订单项
	public List<OrderItem> getO_ItemById(int o_id){
		GoodDetailDao gdd=new GoodDetailDao();
		List<OrderItem> orderItems = new ArrayList<>();
		 Connection conn = DBTools.getInstance().getConnection();
		String sql="select * from tbl_order_item  where order_id=?";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps=conn.prepareStatement(sql);
			ps.setInt(1, o_id);
			rs=ps.executeQuery();
			while(rs.next())
			{
				OrderItem item=new OrderItem();
				item.setItemId(rs.getInt(1));
				item.setOrderId(rs.getInt(2));
				Goods goods = gdd.getGoodByGid(rs.getInt(3));
				item.setGoods(goods);
				item.setGoodNumber(rs.getInt(4));
				item.setTotal_price(rs.getDouble(5));
				orderItems.add(item);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBTools.getInstance().closeConnection(conn, ps, rs);
		}
		return orderItems;
	}
	public int getGidByOid(int o_id)
	{
		int g_id=0;
		 Connection conn = DBTools.getInstance().getConnection();
		String sql="select good_id from tbl_order_item where order_id=?";
		PreparedStatement ps=null;
		ResultSet rs =null;
		try {
			ps=conn.prepareStatement(sql);
			ps.setInt(1, o_id);
			rs=ps.executeQuery();
			if(rs.next())
			{
				g_id=rs.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally {
			DBTools.getInstance().closeConnection(conn, ps, rs);
		}
		return g_id;
	}
	
	//添加订单项和订单信息
	public void addOrderItem(List<OrderItem> itemList, Order order) {
	    Connection conn = DBTools.getInstance().getConnection();
		String sql = "insert into TBL_ORDER_DETAIL(ORDER_ID, ID, ADDRESS_ID, START_TIME, END_TIME) "
				+ "values(SQ_ORDER_ID.nextval, ?, ?, sysdate, sysdate) ";  //需要先插入订单，获取订单的当前序列值
		String sql2 = "insert into TBL_ORDER_ITEM values(SQ_ORDERITEM_ID.nextval, SQ_ORDER_ID.currval,?,?,?)";
		PreparedStatement ps = null;
		PreparedStatement ps2 = null;
		
		try {
			ps = conn.prepareStatement(sql);
			ps2 = conn.prepareStatement(sql2);
			
			ps.setInt(1, order.getUserId());
			ps.setInt(2, order.getUserAddress().getAddressId());
			ps.executeUpdate();
			
			for(int i=0; i<itemList.size(); i++) {
				ps2.setInt(1, itemList.get(i).getGoods().getGoodId());
				ps2.setInt(2, itemList.get(i).getGoodNumber());
				ps2.setDouble(3, itemList.get(i).getTotal_price());
				ps2.executeUpdate();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBTools.getInstance().closeConnection(conn, ps2, null);
		}
	}
	
}
